package cn.com.dpc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.com.dpc.adapter.LvButtonAdapter;
import cn.com.dpc.adapter.TableAdapter;
import cn.com.dpc.adapter.TableAdapter.TableCell;
import cn.com.dpc.adapter.TableAdapter.TableRow;
import cn.com.dpc.bean.Alarm;
import cn.com.dpc.bean.User;
import cn.com.dpc.util.DataService;
import cn.com.dpc.util.HttpGet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class AlarmNewActivity extends Activity {
	ListView lv;
	private String resultStr = "";
	private int pageRecorders = 10;
	private int page = 1;

	private List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
	private List<HashMap<String, Object>> listItemTmp = new ArrayList<HashMap<String, Object>>();
	private SimpleAdapter m_adapter;

	public AlertDialog registerdialog = null;
	public ProgressDialog m_Dialog = null;

	private ProgressBar progressBar = null;
	private LinearLayout loadingLayout = null;
	private int m_nLastItem = 0; // 行号
	private boolean isLoading = false; // 是否正在加载

	LvButtonAdapter listItemAdapter = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarmnew);

		lv = (ListView) this.findViewById(R.id.ListView21);

		loading();

		showList();
	}

	private void showList() {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... arg0) {
				try {
					User user = DataService.queryUser(AlarmNewActivity.this);
					resultStr = HttpGet
							.getResult(
									"http://"
											+ user.getIp()
											+ "/ROOT_V3.1_ANDROID/andriod!findNewAlarm.do?userId="
											+ user.getUserId() + "&page="
											+ page + "&pageRecorders="
											+ pageRecorders,
									AlarmNewActivity.this, "utf8");
					Log.v("dpc.AlarmNewActivity.resultStr", resultStr);
					return true;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				closeProgressBar();
				if (result) {

					try {
						// 每行的数据
						JSONObject jsonObject = new JSONObject(resultStr);
						JSONArray jsonArray = jsonObject.getJSONArray("datas");

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject jo = jsonArray.getJSONObject(i);

							HashMap<String, Object> map = new HashMap<String, Object>();
							if (jo.has("name") && jo.has("stateName")
									&& jo.has("stationName")
									&& jo.has("devName")) {
								map.put("name",
										jo.getString("name")
												+ jo.getString("stateName")
												+ "("
												+ jo.getString("stationName")
												+ "|" + jo.getString("devName")
												+ ")");
							} else {
								continue;
							}
							if (jo.has("alarmTime")) {
								map.put("confirmtime",
										jo.getString("alarmTime"));
							} else {
								map.put("confirmtime", "");
							}
							if (jo.has("confirmtime")) {
								map.put("alarmtime",
										jo.getString("confirmtime"));
							} else {
								map.put("alarmtime", " ");
							}
							map.put("url", jo.toString());
							map.put("alarmadd", R.drawable.alarmadd_selector);
							listItem.add(map);
						}

						m_adapter = new SimpleAdapter(AlarmNewActivity.this,
								listItem,// 数据源
								R.layout.listconfalarm,// ListItem的XML实现
								// 动态数组与ImageItem对应的子项
								new String[] { "name", "alarmtime",
										"confirmtime", "url", "alarmadd" },
								// ImageItem的XML文件里面的一个ImageView,两个TextView ID
								new int[] { R.id.alarmname, R.id.alarmtime,
										R.id.confirmtime, R.id.url,
										R.id.alarmadd });

						listItemAdapter = new LvButtonAdapter(
								AlarmNewActivity.this, listItem,
								R.layout.listconfalarm, new String[] { "name",
										"alarmtime", "confirmtime", "url",
										"alarmadd" }, new int[] {
										R.id.alarmname, R.id.alarmtime,
										R.id.confirmtime, R.id.url,
										R.id.alarmadd });

						lv.removeFooterView(loadingLayout);
						lv.addFooterView(loadingLayout);
						lv.setAdapter(listItemAdapter);

						if (jsonArray.length() < pageRecorders) {
							lv.removeFooterView(loadingLayout);
							listItemAdapter.notifyDataSetChanged();
						}

						// 添加点击
						lv.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int position, long arg3) {

								try {
									String url = (String) listItem
											.get(position).get("url");
									JSONObject jo = new JSONObject(url);
									Alarm alarm = new Alarm();
									alarm.setStationName(jo
											.getString("stationName"));
									alarm.setDevName(jo.getString("devName"));
									alarm.setAlmInfo(jo.getString("name")
											+ jo.getString("stateName"));
									if (jo.has("alarmTime")
											&& jo.getString("alarmTime") != null) {
										alarm.setAlarmTime(new SimpleDateFormat(
												"yyyy-MM-dd HH:mm:ss").parse(jo
												.getString("alarmTime")));
									}
									viewAlarm(alarm);
								} catch (Exception e) {
									// TODO: handle exception
								}
							}
						});

						lv.setOnScrollListener(new OnScrollListener() {
							// 添加滚动条滚到最底部，加载余下的元素
							@Override
							public void onScrollStateChanged(AbsListView view,
									int scrollState) {
								if (m_nLastItem == m_adapter.getCount() + 1
										&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
									loadingLayout.setVisibility(View.VISIBLE);
									if (!isLoading) {
										isLoading = true;
										LoadItems();
									}
								}
							}

							@Override
							public void onScroll(AbsListView view,
									int firstVisibleItem, int visibleItemCount,
									int totalItemCount) {
								m_nLastItem = firstVisibleItem
										+ visibleItemCount;
							}
						});

					} catch (Exception e) {
						e.printStackTrace();
					}

				} else {
					Toast.makeText(AlarmNewActivity.this, "数据加载失败！",
							Toast.LENGTH_SHORT).show();
				}

			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showProgressBar();
			}

		}.execute();

	}

	private void LoadItems() {
		page++;
		new Thread() {
			public void run() {
				try {
					listItemTmp.clear();
					User user = DataService.queryUser(AlarmNewActivity.this);
					resultStr = HttpGet
							.getResult(
									"http://"
											+ user.getIp()
											+ "/ROOT_V3.1_ANDROID/andriod!findNewAlarm.do?userId="
											+ user.getUserId() + "&page="
											+ page + "&pageRecorders="
											+ pageRecorders,
									AlarmNewActivity.this, "utf8");

					JSONObject jsonObject = new JSONObject(resultStr);
					JSONArray jsonArray = jsonObject.getJSONArray("datas");
					Log.v("dpc.ParamsActivity.jsonArrayLength",
							jsonArray.length() + " ");

					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jo = jsonArray.getJSONObject(i);

						HashMap<String, Object> map = new HashMap<String, Object>();
						if (jo.has("name") && jo.has("stateName")
								&& jo.has("stationName") && jo.has("devName")) {
							map.put("name",
									jo.getString("name")
											+ jo.getString("stateName") + "("
											+ jo.getString("stationName") + "|"
											+ jo.getString("devName") + ")");
						} else {
							continue;
						}
						if (jo.has("alarmTime")) {
							map.put("confirmtime", jo.getString("alarmTime"));
						} else {
							map.put("confirmtime", "");
						}
						if (jo.has("confirmtime")) {
							map.put("alarmtime", jo.getString("confirmtime"));
						} else {
							map.put("alarmtime", " ");
						}
						map.put("url", jo.toString());
						map.put("alarmadd", R.drawable.alarmadd_selector);
						listItemTmp.add(map);
					}
					if (jsonArray.length() > 0) {
						listItem.addAll(listItemTmp);
						m_handler1.sendEmptyMessage(0);
					} else {
						m_handler2.sendEmptyMessage(0);
					}
				} catch (Exception e) {
				}
			}
		}.start();
	}

	private Handler m_handler1 = new Handler() {
		public void handleMessage(Message msg) {
			try {
				listItemAdapter.notifyDataSetChanged();
				loadingLayout.setVisibility(View.GONE);
				isLoading = false;
			} catch (Exception e) {
				new AlertDialog.Builder(AlarmNewActivity.this).setTitle("对话框")
						.setMessage("服务器故障，请稍候再试！")
						.setPositiveButton("确定", null).show();
			}
		}
	};
	private Handler m_handler2 = new Handler() {
		public void handleMessage(Message msg) {
			try {
				lv.removeFooterView(loadingLayout);
				listItemAdapter.notifyDataSetChanged();
				isLoading = false;
			} catch (Exception e) {
				new AlertDialog.Builder(AlarmNewActivity.this).setTitle("对话框")
						.setMessage("服务器故障，请稍候再试！")
						.setPositiveButton("确定", null).show();
			}
		}
	};

	private void viewAlarm(Alarm alarm) {
		AlertDialog.Builder ad = new AlertDialog.Builder(
				AlarmNewActivity.this.getParent());
		ad.setTitle("告警详情");
		View view = View.inflate(AlarmNewActivity.this, R.layout.confalarmview,
				null);

		TextView stationNameEt = (TextView) view.findViewById(R.id.stationName);
		TextView devNameEt = (TextView) view.findViewById(R.id.devName);
		TextView paramNameEt = (TextView) view.findViewById(R.id.paramName);
		TextView alarmTimeEt = (TextView) view.findViewById(R.id.alarmTimeName);
		stationNameEt.setText(alarm.getStationName());
		devNameEt.setText(alarm.getDevName());
		paramNameEt.setText(alarm.getAlmInfo());
		if (alarm.getAlarmTime() != null) {
			alarmTimeEt.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(alarm.getAlarmTime()));
		}

		ad.setView(view);
		registerdialog = ad.create();

		registerdialog.setButton2("关闭",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						registerdialog.dismiss();
						// MainActivity.this.finish();
					}
				});
		registerdialog.show();
	}

	public void showProgressBar() {
		AnimationSet set = new AnimationSet(true);

		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);
		loading.setVisibility(View.VISIBLE);
		loading.setLayoutAnimation(controller);
	}

	public void closeProgressBar() {

		AnimationSet set = new AnimationSet(true);

		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);

		loading.setLayoutAnimation(controller);

		loading.setVisibility(View.INVISIBLE);
	}

	public void showProgressBar(String title) {
		TextView loading = (TextView) findViewById(R.id.txt_loading);
		loading.setText(title);
		showProgressBar();
	}

	private void loading() {
		LinearLayout searchLayout = new LinearLayout(this);
		searchLayout.setOrientation(LinearLayout.HORIZONTAL);
		progressBar = new ProgressBar(this);
		progressBar.setPadding(0, 0, 15, 0);
		progressBar.setProgressDrawable(getResources().getDrawable(
				R.drawable.progressbar));
		searchLayout.addView(progressBar, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		TextView textView = new TextView(this);
		textView.setText("加载中...");
		textView.setGravity(Gravity.CENTER_VERTICAL);
		searchLayout.addView(textView, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
		searchLayout.setGravity(Gravity.CENTER);
		loadingLayout = new LinearLayout(this);
		loadingLayout.addView(searchLayout, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		loadingLayout.setGravity(Gravity.CENTER);
	}
}
